package com.util;


import com.KiwiResumeApplication;
import com.config.WechatConfig;
import lombok.Getter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Component
public class VerificationCodeManager {
    @Autowired
    private WechatConfig wxConfig;
    private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int CODE_LENGTH = 6; // 验证码长度
    private static final int EXPIRATION_TIME_SECONDS = 60; // 验证码过期时间（秒）

    private final Map<String, VerificationCode> verificationCodeMap = new HashMap<>();
    //创建1个线程的线程池，清理过期动态码在单独的线程中执行
    private final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);


    /**
     * 生成随机动态码
     * @return code
     */
    public String generateCode() {
        StringBuilder code = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < CODE_LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            code.append(CHARACTERS.charAt(index));
        }

        return code.toString();
    }

    /**
     * 发送验证码
     * @param userId
     */
    public void sendCodeToUser(String userId, String dynamicCode) {
        //System.out.println("Ocd"+wxConfig.getAppid());

        // 创建WxMpService实例，使用注入的微信配置信息
        WxMpService wxMpService = new WxMpServiceImpl();
        WxMpDefaultConfigImpl config = new WxMpDefaultConfigImpl();
        config.setAppId(wxConfig.getAppid());
        config.setSecret(wxConfig.getSecret());
        wxMpService.setWxMpConfigStorage(config);

        // 配置公众号信息

        // 在实际应用中，这里应该调用微信公众号的接口来发送验证码给用户
        // 使用微信Java SDK发送文本消息
        WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(userId).content("您的验证码是：" + dynamicCode).build();

        try {
            wxMpService.getKefuService().sendKefuMessage(message);
            System.out.println("向微信用户发送验证码成功：" + userId + " - 验证码：" + dynamicCode);
        } catch (Exception e) {
            System.err.println("向微信用户发送验证码失败：" + e.getMessage());
        }
    }
    /**
     * 验证动态码 内存
     * @param userId
     * @param inputCode
     * @return
     */
    public boolean verifyCode(String userId, String inputCode) {
        VerificationCode storedCode = verificationCodeMap.get(userId);

        // 检查是否找到存储的动态码
        if (storedCode == null) {
            return false; // 验证失败
        }

        // 获取存储的动态码和过期时间
        String code = storedCode.getCode();
        long expirationTime = storedCode.getExpirationTime();

        // 检查动态码是否过期
        long currentTime = System.currentTimeMillis() / 1000;
        if (currentTime > expirationTime) {
            verificationCodeMap.remove(userId); // 过期后删除验证码
            return false; // 验证失败
        }

        // 检查动态码是否与输入的匹配
        if (code.equals(inputCode)) {
            verificationCodeMap.remove(userId); // 验证成功后删除验证码
            return true;
        }

        return false; // 验证失败
    }

    /**
     * 动态码
     */
    @Getter
    private static class VerificationCode {
        private final String code;
        private final long expirationTime;

        public VerificationCode(String code, long expirationTime) {
            this.code = code;
            this.expirationTime = expirationTime;
        }

    }

    /**
     * 定期清理过期动态码
     */
    public VerificationCodeManager() {
        // 每隔一段时间（例如每分钟）清理一次过期验证码
        executorService.scheduleAtFixedRate(this::cleanExpiredCodes, 1, 1, TimeUnit.MINUTES);
    }

    public void cleanExpiredCodes(){
        long currenttime = System.currentTimeMillis()/1000;  //当前时间/秒
        Iterator<Map.Entry<String,VerificationCode>> interator = verificationCodeMap.entrySet().iterator();
        //遍历验证码Map，删除过期验证码
        while(interator.hasNext()){
            Map.Entry<String,VerificationCode> entry = interator.next();
            VerificationCode code = entry.getValue();
            if(code.getExpirationTime() < currenttime){
                interator.remove();
            }
        }

    }

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(KiwiResumeApplication.class, args);

        // 从上下文中获取VerificationCodeManager的实例
        VerificationCodeManager codeManager = context.getBean(VerificationCodeManager.class);
        //VerificationCodeManager codeManager = new VerificationCodeManager();
        String userId = "user123";
        //创建Jedis连接
        //Jedis jedis = new Jedis("localhost"); //Redis服务器配置
        String code = codeManager.generateCode();
        // 模拟用户关注公众号后发送验证码
        codeManager.sendCodeToUser(userId,code);

        // 模拟用户输入验证码进行验证
        String userInputCode = "ABC123";
        boolean isValid = codeManager.verifyCode(userId, userInputCode);

        if (isValid) {
            System.out.println("Verification successful. Allowing user to log in.");
        } else {
            System.out.println("Verification failed. Please try again.");
        }
    }
}

